package com.situ.crm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.crm.mapper.PermissionMapper;
import com.situ.crm.pojo.entity.Permission;
import com.situ.crm.pojo.vo.LayUISelectMVO;
import com.situ.crm.service.IPermissionService;
import com.situ.crm.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl implements IPermissionService {
	@Autowired
	private PermissionMapper permissionMapper;
	
	@Override
	public JSONResult selectByPage(Integer page, Integer limit, Permission permission) {
		//1、使用PageHelper插件设置分页
		PageHelper.startPage(page, limit);
		// int offset = (page - 1) * limit;
		//2、执行查询
		List<Permission> list = permissionMapper.selectByPage(permission);
		//3、使用PageInfo对结果进行包装
		PageInfo pageInfo = new PageInfo(list);
		Integer count = (int) pageInfo.getTotal();//得到总数量

		return  JSONResult.ok("查询成功", list, count);
	}

	@Override
	public boolean deleteById(Integer id) {
		int count = permissionMapper.deleteByPrimaryKey(id);
		return  count == 1 ? true : false;
	}

	@Override
	public boolean deleteAll(String ids) {
		String[] idArray = ids.split(",");
		int count = permissionMapper.deleteAll(idArray);
		return  count == idArray.length ? true : false;
	}

	@Override
	public boolean add(Permission permission) {
		int count = permissionMapper.insert(permission);
		return  count == 1 ? true : false;
	}

	@Override
	public Permission selectByPrimaryKey(Integer permissionId) {
		return permissionMapper.selectByPrimaryKey(permissionId);
	}

	@Override
	public JSONResult selectAllPermisssions() {
		// pageList没有传递任何参数，相当于查找所有
		List<Permission> permissions =
				permissionMapper.selectByPage(new Permission());
		// SelectM需要的结构[{"id":12,"name":"长者","status":0},{"id":11,"name":"长者1","status":1}]，
		// status就是选中和不选中状态
		// 所以在这里转换一下
		List<LayUISelectMVO> list = new ArrayList<>();
		for (Permission permission : permissions) {
			LayUISelectMVO layUISelectMVO = new LayUISelectMVO();
			layUISelectMVO.setId(permission.getId());
			layUISelectMVO.setName(permission.getName());
			layUISelectMVO.setStatus(1);
			list.add(layUISelectMVO);
		}

		return JSONResult.ok("查询成功", list);
	}

}
